package com.sky.zzh.setting;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHPut;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.SHDialog.DialogItemClickListener;
import com.sky.widget.SHToast;
import com.sky.zzh.BaseFragment;
import com.sky.zzh.R;
import com.sky.zzh.util.AsyncTaskImageLoad;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.HttpUtils;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.CircularImage;

/**
 * 个人信息
 * 
 * @author skypan
 * 
 */
public class EditSelfInfoFragment extends BaseFragment implements ITaskListener {

	private ImageView mBtnback, mBtnRight;
	private CircularImage mIvHead;
	private TextView mTvUpdate;
	private LinearLayout mLlBirth, mLlSex;
	private TextView mTvBirth, mTvSex, mTvCellphone;
	private SHPut updateTask;
	private SHGet infoTask;
	private EditText mEtUserName, mEtTel, mEtAddress, mEtEmer, mEtEmerPhone, mEtHeight, mEtWeight;
	private final int TAKE_PICTURE = 1;// 拍照
	private final int CHOOSE_PICTURE = 2;// 相册
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				// 上传成功
				SHDialog.dismissProgressDiaolg();
				SHToast.showToast(getActivity(), "上传成功");
				ConfigDefinition.photourl = ConfigDefinition.URL+"file/DownloadFile/"+UserInfoManager.getInstance().getUserId();
				Intent intent = new Intent();
				intent.setAction("name_change");
				getActivity().sendBroadcast(intent);
				LoadImage(mIvHead, ConfigDefinition.URL+"file/DownloadFile/"+UserInfoManager.getInstance().getUserId());
				break;
			case 1:
				SHDialog.dismissProgressDiaolg();
				SHToast.showToast(getActivity(), "图片格式不支持");
				break;
			}
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_selfinfo_edit, container, false);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		mBtnback = (ImageView) view.findViewById(R.id.btn_back);
		mBtnback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				getActivity().finish();
			}
		});
		mIvHead = (CircularImage) view.findViewById(R.id.iv_head);
		mTvUpdate = (TextView) view.findViewById(R.id.tv_update);
		mLlBirth = (LinearLayout) view.findViewById(R.id.ll_birth);
		mTvBirth = (TextView) view.findViewById(R.id.tv_birth);
		mLlSex = (LinearLayout) view.findViewById(R.id.ll_sex);
		mTvSex = (TextView) view.findViewById(R.id.tv_sex);
		mBtnRight = (ImageView) view.findViewById(R.id.btn_right);
		mEtUserName = (EditText) view.findViewById(R.id.et_username);
		mEtTel = (EditText) view.findViewById(R.id.et_tel);
		mEtAddress = (EditText) view.findViewById(R.id.et_address);
		mEtEmer = (EditText) view.findViewById(R.id.et_emer);
		mEtEmerPhone = (EditText) view.findViewById(R.id.et_emer_phone);
		mTvCellphone = (TextView) view.findViewById(R.id.tv_cellphone);
		mEtHeight = (EditText) view.findViewById(R.id.et_height);
		mEtWeight = (EditText) view.findViewById(R.id.et_weight);
		
		if(!"normal".equals(UserInfoManager.getInstance().getLoginType())){
			mEtUserName.setEnabled(false);
		}

		setListeners();
		requestInfo();
//		LoadImage(mIvHead, ConfigDefinition.URL+"file/DownloadFile/"+UserInfoManager.getInstance().getUserId());
		if("qq".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoQQ());
		}else if("sina".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoSina());
		}else if("weixin".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoWeixin());
		}else{
			LoadImage(mIvHead, ConfigDefinition.photourl);
		}
		
		if(!"normal".equals(UserInfoManager.getInstance().getLoginType())){
			mTvUpdate.setVisibility(View.GONE);
		}else{
			mTvUpdate.setVisibility(View.VISIBLE);
		}
	}

	private class OnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.iv_head:
			case R.id.tv_update:
				if("normal".equals(UserInfoManager.getInstance().getLoginType())){
					final String[] items = new String[] { "相册", "拍照" };
					SHDialog.showActionSheet(getActivity(), "选择照片来源", items, new DialogItemClickListener() {

						@Override
						public void onSelected(String result) {
							// TODO Auto-generated method stub
							if (result.equals(items[0])) {
								Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
								startActivityForResult(intent, CHOOSE_PICTURE);
							} else {
								Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
								Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "zzh.png"));
								openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
								startActivityForResult(openCameraIntent, TAKE_PICTURE);
							}
						}
					});
				}
				break;
			case R.id.ll_birth:
				// CalendarDialog dia = new CalendarDialog(getActivity(), new
				// CalendarResultListener() {
				//
				// @Override
				// public void onCalendarResult(Dialog d, String date) {
				// // TODO Auto-generated method stub
				// mTvBirth.setText(date);
				// d.dismiss();
				// }
				// });
				// dia.show();
				if(CommonUtil.isEmpty(mTvBirth.getText().toString().trim())){
					DatePickerDialog dpd = new DatePickerDialog(getActivity(), new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
							// TODO Auto-generated method stub
							mTvBirth.setText(arg1 + "-" + CommonUtil.getDoubleNum(arg2 + 1) + "-" + CommonUtil.getDoubleNum(arg3));
						}
					}, 1980, 01, 01);
					dpd.show();
				}else{
					DatePickerDialog dpd = new DatePickerDialog(getActivity(), new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
							// TODO Auto-generated method stub
							mTvBirth.setText(arg1 + "-" + CommonUtil.getDoubleNum(arg2 + 1) + "-" + CommonUtil.getDoubleNum(arg3));
						}
					}, Integer.valueOf(mTvBirth.getText().toString().substring(0, 4)), Integer.valueOf(mTvBirth.getText().toString().substring(5, 7)) - 1, Integer.valueOf(mTvBirth.getText().toString()
							.substring(8, 10)));
					dpd.show();
				}
				break;
			case R.id.ll_sex:
				final String[] items_sex = new String[] { "男", "女" };
				SHDialog.showActionSheet(getActivity(), "选择性别", items_sex, new DialogItemClickListener() {

					@Override
					public void onSelected(String result) {
						// TODO Auto-generated method stub
						if (result.equals(items_sex[0])) {
							mTvSex.setText("男");
						} else {
							mTvSex.setText("女");
						}
					}
				});
				break;
			case R.id.btn_right:
				if(CommonUtil.isEmpty(mTvBirth.getText().toString().trim())){
					SHToast.showToast(getActivity(), "请填写生日信息");
					return;
				}
				if(CommonUtil.isEmpty(mEtHeight.getText().toString().trim())){
					SHToast.showToast(getActivity(), "请填写身高信息");
					return;
				}
				if(CommonUtil.isEmpty(mEtWeight.getText().toString().trim())){
					SHToast.showToast(getActivity(), "请填写体重信息");
					return;
				}
//				SHDialog.ShowProgressDiaolg(getActivity());
				updateTask = new SHPut();
				updateTask.setUrl(ConfigDefinition.URL + "user/ModifyUserInfo");
				updateTask.setListener(EditSelfInfoFragment.this);
				updateTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
				updateTask.getTaskArgs().put("UserName", mEtUserName.getText().toString().trim());
				updateTask.getTaskArgs().put("Birthday", mTvBirth.getText().toString().trim());
				updateTask.getTaskArgs().put("Gender", mTvSex.getText().toString().trim());
				updateTask.getTaskArgs().put("Height", mEtHeight.getText().toString().trim());
				updateTask.getTaskArgs().put("Weight", mEtWeight.getText().toString().trim());
				updateTask.getTaskArgs().put("Telephone", mEtTel.getText().toString().trim());
				updateTask.getTaskArgs().put("Address", mEtAddress.getText().toString().trim());
				updateTask.getTaskArgs().put("EmergencyContact", mEtEmer.getText().toString().trim());
				updateTask.start();
				break;
			}
		}
	}

	private void setListeners() {
		OnClick onClick = new OnClick();
		mIvHead.setOnClickListener(onClick);
		mBtnRight.setOnClickListener(onClick);
		mTvUpdate.setOnClickListener(onClick);
		mLlBirth.setOnClickListener(onClick);
		mLlSex.setOnClickListener(onClick);
	}

	private void requestInfo() {
//		SHDialog.ShowProgressDiaolg(getActivity());
		infoTask = new SHGet();
		infoTask.setUrl(ConfigDefinition.URL + "user/UserInfo");
		infoTask.setListener(this);
		infoTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
		infoTask.start();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
			bitmapOptions.inSampleSize = 3;
			switch (requestCode) {
			case 0:
				requestInfo();
				break;
			case TAKE_PICTURE:// 拍照

				String picPath = Environment.getExternalStorageDirectory() + "/zzh.png";
//				Bitmap bitmap_tack = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/zzh.png", bitmapOptions);
				// mIvPhoto.setImageBitmap(bitmap_tack);
				// SHDialog.ShowProgressDiaolg(this);
				// new Thread(new Runnable() {
				//
				// @Override
				// public void run() {
				// // TODO Auto-generated method stub
				// String result_take =
				// HttpUtils.submitPostImg(ConfigDefinition.URL+"file/UploadFile/"+UserInfoManager.getInstance().getUserId(),
				// Environment.getExternalStorageDirectory() + "/zzh.png");
				// System.out.println("result:"+result_take);
				// mHandler.sendEmptyMessage(0);
				// }
				// }).start();
				upload(picPath);
				break;
			case CHOOSE_PICTURE:// 相册
				Uri originalUri = data.getData();
				String[] filePathColumns = { MediaStore.Images.Media.DATA };
				Cursor c = getActivity().getContentResolver().query(originalUri, filePathColumns, null, null, null);
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				final String picturePath = c.getString(columnIndex);
				// picPath = picturePath;
				c.close();
				// Bitmap bitmap_choose = BitmapFactory.decodeFile(picturePath,
				// bitmapOptions);
				// mIvPhoto.setImageBitmap(bitmap_choose);
				upload(picturePath);
				break;
			}
		}
	}
	
	private void upload(final String picPath) {
		SHDialog.ShowProgressDiaolg(getActivity(), "正在上传...");
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String result = HttpUtils.submitPostImg(ConfigDefinition.URL + "file/UploadFile/" + UserInfoManager.getInstance().getUserId(), picPath);
				System.out.println("result:" + result);
				try {
					JSONObject json = new JSONObject(result);
					if ("200".equals(json.optString("ReturnCode"))) {
						// Intent intent = new
						// Intent(RegisterActivity.this,ZZHMainActivity.class);
						// startActivity(intent);
						mHandler.sendEmptyMessage(0);
					} else {
						mHandler.sendEmptyMessage(1);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	
	
	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		// TODO Auto-generated method stub
		SHDialog.dismissProgressDiaolg();
		System.out.println(task.getResult());
		if (task == updateTask) {
			JSONObject json = new JSONObject(task.getResult().toString());
			if ("200".equals(json.optString("ReturnCode"))) {
				SHToast.showToast(getActivity(), "保存成功");
				UserInfoManager.getInstance().setUsername(mEtUserName.getText().toString().trim());
				UserInfoManager.getInstance().sync(getActivity(), true);
				Intent intent = new Intent();
				intent.setAction("name_change");
				getActivity().sendBroadcast(intent);
				getActivity().setResult(Activity.RESULT_OK);
				getActivity().finish();
			}
		} else if (task == infoTask) {
			JSONObject json = new JSONObject(task.getResult().toString());
			if ("200".equals(json.optString("ReturnCode"))) {
				JSONObject infoJson = json.optJSONObject("UserInfo");
//				if (!CommonUtil.isEmpty(UserInfoManager.getInstance().getUsername())) {
//					mEtUserName.setText(UserInfoManager.getInstance().getUsername());
//				} else {
//					mEtUserName.setText(infoJson.optString("UserName"));
//				}
				
				if("qq".equals(UserInfoManager.getInstance().getLoginType())){
					mEtUserName.setText(UserInfoManager.getInstance().getNickQQ());
				}else if("sina".equals(UserInfoManager.getInstance().getLoginType())){
					mEtUserName.setText(UserInfoManager.getInstance().getNickSina());
				}else if("weixin".equals(UserInfoManager.getInstance().getLoginType())){
					mEtUserName.setText(UserInfoManager.getInstance().getNickWeixin());
				}else{
					mEtUserName.setText(infoJson.optString("UserName"));
				}
				
//				mEtUserName.setText(infoJson.optString("UserName"));
				mTvBirth.setText(infoJson.optString("Birthday"));
				mTvSex.setText(infoJson.optString("Gender"));
				mTvCellphone.setText(infoJson.optString("CellPhone"));
				mEtTel.setText(infoJson.optString("Telephone"));
				mEtEmer.setText(infoJson.optString("EmergencyContact"));
				mEtEmerPhone.setText(infoJson.optString("Telephone"));
				mEtHeight.setText(infoJson.optString("Height"));
				mEtWeight.setText(infoJson.optString("Weight"));
				mEtAddress.setText(infoJson.optString("Address"));
			}
		}
	}

	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub

	}
	
	 private void LoadImage(ImageView img, String path) 
     {
         //异步加载图片资源
         AsyncTaskImageLoad async=new AsyncTaskImageLoad(img);
         //执行异步加载，并把图片的路径传送过去
         async.execute(path);
         
     }
}
